const WebSocket = require('ws');
const databaseService = require('./database.js');

class WebSocketService {
    constructor() {
        this.wss = null;
        this.clients = new Set();
    }

    initialize(server) {
        // 初始化数据库连接
        databaseService.connect()
            .then(() => {
                // 初始化WebSocket服务
                this.wss = new WebSocket.Server({ server });
                this.wss.on('connection', (ws, request) => {
                    console.log('新的客户端连接');
                    this.clients.add(ws);

                    ws.on('message', async (data) => {
                        try {
                            const message = JSON.parse(data);
                            console.log('收到消息:', message);
                            // 保存到数据库(排除元事件)
                            if (message.post_type !== 'meta_event') {
                                await databaseService.save(message);
                            }
                        } catch (error) {
                            console.error('处理消息时出错:', error);
                        }
                    });

                    ws.on('close', () => {
                        console.log('客户端断开连接');
                        this.clients.delete(ws);
                    });
                });

                console.log('WebSocket服务器已启动');
            })
            .catch(error => {
                console.error('启动失败:', error);
                process.exit(1);
            });

        // 优雅关闭
        process.on('SIGINT', async () => {
            console.log('正在关闭服务器...');
            server.close(() => {
                console.log('服务器已关闭');
                process.exit(0);
            });
        });
    }
}

module.exports = new WebSocketService();
